package com.miplus.ccrm.report.service.cti;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.miplus.ccrm.common.*;
import com.miplus.ccrm.report.controller.vo.cti.*;
import com.miplus.ccrm.report.controller.vo.evt.CtiCallEvtVo;
import com.miplus.ccrm.report.feign.FiImpAddVo;
import com.miplus.ccrm.report.feign.ICoreFeign;
import com.miplus.ccrm.report.pojo.CtiCallhist;
import com.miplus.ccrm.report.mapper.CtiCallhistMapper;
import com.miplus.ccrm.report.service.ExportService;
import com.miplus.ccrm.report.utils.SpringContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;

/**
* @author pc
* @description 针对表【cti_callhist(CC呼叫记录表)】的数据库操作Service实现
* @createDate 2024-04-26 16:45:08
*/
@Slf4j
@Service
public class CtiCallhistServiceImpl extends MPJBaseServiceImpl<CtiCallhistMapper, CtiCallhist>
    implements CtiCallhistService{
    @Resource
    private ExportService exportService;
    @Resource
    private ICoreFeign iCoreFeign;

    @Override
    public IPage<CallResVo> callList(JSysUser user, CallReqVo paras)
    {
        String $usrid=user.getUsrid();
        String phnstar= JUsrPerm.getPermission(user, JUsrPerm.DISSTAR_PHN);

        return selectJoinListPage(new Page<>(paras.getPageNum(), paras.getPageSize()),
                CallResVo.class,
                new MPJLambdaWrapper<CtiCallhist>()
                        .selectAs(String.format("fi_starSecu('%s','%s',t.ani,'%s')",$usrid,JUsrPerm.DISSTAR_PHN,phnstar), CallResVo::getAni)
                        .selectAs(String.format("fi_starSecu('%s','%s',t.dnis,'%s')",$usrid,JUsrPerm.DISSTAR_PHN,phnstar), CallResVo::getDnis)
                        .selectAs("fun_getgrpname(t.usrid)", CallResVo::getGrpname)
                        .selectAs("fun_getusername(t.usrid)", CallResVo::getUsrname)
                        .select(CtiCallhist::getUcallid,CtiCallhist::getCallid,CtiCallhist::getActivespan,CtiCallhist::getQuespan,CtiCallhist::getRingspan,
                                CtiCallhist::getCrdt,CtiCallhist::getAgentid,CtiCallhist::getCallgrp,CtiCallhist::getCalltype,CtiCallhist::getCallresult,
                                CtiCallhist::getDn,CtiCallhist::getDntype,CtiCallhist::getHangupcause,CtiCallhist::getRecordurl,CtiCallhist::getUsrid)
                        .eq(JPubUtils.IsNotEmpty(paras.getUsrid()),CtiCallhist::getUsrid,paras.getUsrid())
                        .eq(JPubUtils.IsNotEmpty(paras.getCalltype()),CtiCallhist::getCalltype,paras.getCalltype())
                        .between(JPubUtils.IsNotEmpty(paras.getStartdt()), CtiCallhist::getCrdt,JPubUtils.StringToDate(paras.getStartdt()),JPubUtils.StringToDate(paras.getEnddt()))
                        .ge(JPubUtils.IsNotEmpty(paras.getTalkspan1()),CtiCallhist::getActivespan,paras.getTalkspan1())
                        .le(JPubUtils.IsNotEmpty(paras.getTalkspan2()),CtiCallhist::getActivespan,paras.getTalkspan2())
                        .apply(JPubUtils.IsNotEmpty(paras.getPhone()),"(t.ani={0} or t.dnis={0})",paras.getPhone())
                        .apply(JPubUtils.IsNotEmpty(paras.getGrpid()),"fc_hasUsrInGroup(t.usrid,{0})>0",paras.getGrpid())
                        .isNotNull(CtiCallhist::getRecordurl)
                        .orderByAsc(CtiCallhist::getCrdt)
        );
    }

    @Override
    public CmdResVo callAdd(CtiCallEvtVo paras)
    {
        CtiCallhist callhist=new CtiCallhist();
        callhist.setCallid(paras.getCallId());
        callhist.setAni(paras.getCalling());
        callhist.setDnis(paras.getCalled());
        callhist.setAgentid(paras.getAgentId());
        if(JPubUtils.IsNotEmpty(paras.getAgentId())) {
            String usrid=baseMapper.getUsrByAgentID(paras.getAgentId());
            log.info("callAdd：agentid={}->usrid={}",paras.getAgentId(),usrid);
            callhist.setUsrid(usrid);
        }
        callhist.setDn(paras.getDevice());
        callhist.setCalltype("OUT");
        callhist.setDntype("device");
        if(paras.getIsConnected()==1){
            callhist.setCallresult("ACTV");
        }
        else{
            callhist.setCallresult("ABDN");
        }
        if(JPubUtils.IsNotEmpty(paras.getConnectSpan())){
            callhist.setActivespan(BigDecimal.valueOf(paras.getConnectSpan()));
        }
        if(JPubUtils.IsNotEmpty(paras.getRingSpan())){
            callhist.setRingspan(BigDecimal.valueOf(paras.getConnectSpan()));
        }
        callhist.setHangupcause(paras.getHangupCause());
        callhist.setCrdt(paras.getCallStartTime());
        if(paras.getCallEndTime()!=null) {
            callhist.setEnddt(paras.getCallEndTime());
        }
        callhist.setRecordurl(paras.getRecordurl());

        int ret=baseMapper.insert(callhist);

        return new CmdResVo(ret);
    }

    @Override
    public IPage<CallAgDayResVo> repAgentCallDay(String usrid, CallAgDayReqVo paras)
    {
        return baseMapper.quyAgentCallDay(new Page<>(paras.getPageNum(),paras.getPageSize()),usrid,paras);
    }

    //呼叫列表导出
    @Override
    public CmdResVo expCallList(JSysUser user, CallReqVo paras, HttpServletResponse response)
    {
        String $usrid = user.getUsrid();
        int pagesize = paras.getPageSize();
        if (pagesize > JPubUtils.exportMaxCount) {
            paras.setPageSize(JPubUtils.exportMaxCount);
        }
        log.info("expSmsList:pagesize={}",pagesize);

        IPage<CallResVo> pages=callList(user,paras);
        ArrayList arr=new ArrayList();

        String exptempid=JPubUtils.getExpTempID(paras.getExpfilename(),"呼叫列表数据");
        String filename=JPubUtils.getExpFileName(
                paras.getExpfilename(),exptempid
        );
        pages.convert(u->{
            HashMap map=JPubUtils.toExportMap(u);
            if(map!=null) arr.add(map);
            return u;
        });
        CmdResVo resVo=exportService.ToExcel(
                response,
                arr,
                paras.getExpidlist(),
                paras.getExpnamelist(),
                filename,
                $usrid
        );

        int okcount=resVo.getCount();
        if(okcount>0){
            FiImpAddVo addVo=new FiImpAddVo();
            addVo.setBatchid(resVo.getKeyId());
            addVo.setFilename(filename);
            addVo.setTempid(exptempid);
            addVo.setOkcount(okcount);
            String token = SpringContextUtil.getBearerToken();
            iCoreFeign.addImportHist(addVo,token);
        }
        arr.clear();

        return resVo;
    }
}




